import { useRouter } from "vue-router"
import { ref } from "vue"
import { SELECTED_KEYS, OPEN_KEYS } from "@/constant"
import { getSesstionKey, setSesstionKey } from "@/utils"
/**
 * 
 * 1\声明组合式函数
 * 2\外部需要使用的变量或者是函数，必须return
 * 3\外部外入函数，然后解构
 */
export function useMenu(){
    // 路由对象
    const router = useRouter()
    // 路由菜单
    const menuList = ref(router.options.routes)
    // selectedKeys
    const storageSelectedKeys = getSesstionKey(SELECTED_KEYS)
    const selectedKeys = ref(storageSelectedKeys ? JSON.parse(storageSelectedKeys) : [])
    // openKeys
    const storageOpenKeys = getSesstionKey(OPEN_KEYS)
    const openKeys = ref(storageOpenKeys ? JSON.parse(storageOpenKeys) : [])

    // 点击菜单 click
    const useMenuClick = ({ item, key, keyPath }) => {
        selectedKeys.value = [key]
        openKeys.value = [keyPath[0]]
        // 设置SELECTED_KEYS
        setSesstionKey(SELECTED_KEYS, selectedKeys.value)
        // 设置OPEN_KEYS
        setSesstionKey(OPEN_KEYS, openKeys.value)
        // 路由切换
        router.push(key)
    }
    
    return {
        menuList,
        selectedKeys,
        openKeys,
        useMenuClick
    }
}